import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
  Logger,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap, catchError } from 'rxjs/operators';
import { Request, Response } from 'express';

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  private readonly logger = new Logger(LoggingInterceptor.name);

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest<Request>();
    const response = context.switchToHttp().getResponse<Response>();
    const { method, url, body, query, headers } = request;
    const userAgent = request.get('User-Agent') || '';
    const startTime = Date.now();

    // 记录请求信息
    this.logger.log('=== 请求开始 ===');
    this.logger.log(`${method} ${url}`);
    this.logger.log(`用户代理: ${userAgent}`);
    this.logger.log(`请求体: ${JSON.stringify(body)}`);
    this.logger.log(`查询参数: ${JSON.stringify(query)}`);
    this.logger.log(`请求头: ${JSON.stringify(headers)}`);

    return next.handle().pipe(
      tap((data) => {
        const endTime = Date.now();
        const duration = endTime - startTime;
        const statusCode = response.statusCode;

        // 记录响应信息
        this.logger.log('=== 响应信息 ===');
        this.logger.log(`状态码: ${statusCode}`);
        this.logger.log(`响应时间: ${duration}ms`);
        this.logger.log(`响应数据: ${JSON.stringify(data)}`);
        this.logger.log('=== 请求结束 ===');
      }),
      catchError((error) => {
        const endTime = Date.now();
        const duration = endTime - startTime;

        // 记录错误信息
        this.logger.error('=== 请求错误 ===');
        this.logger.error(`错误类型: ${error.constructor.name}`);
        this.logger.error(`错误消息: ${error.message}`);
        this.logger.error(`响应时间: ${duration}ms`);
        this.logger.error(`错误堆栈: ${error.stack}`);
        this.logger.error('=== 请求错误结束 ===');

        throw error;
      }),
    );
  }
} 